package com.example.capsule_chat0322.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.example.capsule_chat0322.R;
import com.example.capsule_chat0322.activity.ChatActivity;
import com.example.capsule_chat0322.activity.OneToOneChatActivity;
import com.example.capsule_chat0322.activity.UserInfoActivity;
import com.example.capsule_chat0322.bean.GlobalRoomBean;
import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.bean.Msg;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.configuration.ActionType;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.global.GlobalChatRoomMap;
import com.example.capsule_chat0322.global.GlobalThreadPool;
import com.example.capsule_chat0322.global.LRUCache;
import com.example.capsule_chat0322.netty.NettyClient;
import com.example.capsule_chat0322.request.MessagesRequest;
import com.example.capsule_chat0322.request.UserInfoRequest;
import com.example.capsule_chat0322.utils.AlterUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

/**
 * @Author zhuzhiming
 * @Date 2022/4/30 19:25
 */
public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHold> {

    public List<Msg> mMsgList;
    private boolean isScrolling = false;
    private Set<File> fileSet;
    private Activity activity;
    private final int USER_INFO_CODE = 0;
    private static final int UPDATE_INFO_CODE = 2;


    static class ViewHold extends RecyclerView.ViewHolder {
        LinearLayout leftLayout;
        //RelativeLayout rightLayout;
        private RelativeLayout rightLayout;
        private LinearLayout self_file_linear;
        private LinearLayout other_file_linear;
        private TextView leftMsg;
        private TextView remind_word;
        private TextView rightMsg;
        private ImageView self_send_image;
        private ImageView other_send_image;
        private ImageView self_avatar;
        private ImageView other_avatar;
        private TextView self_file_desc;
        private TextView other_file_desc;
        private ImageView self_file_image;
        private ImageView self_video_image;
        private ImageView other_video_image;
        private ImageView other_file_image;
        private ImageView self_play_video;
        private ImageView other_play_video;
        private RelativeLayout self_video_relative;
        private RelativeLayout other_video_relative;
        private TextView other_sign;


        public ViewHold(@NonNull View itemView) {
            super(itemView);
            leftLayout = itemView.findViewById(R.id.left_layout);
            rightLayout = itemView.findViewById(R.id.right_layout);
            leftMsg = itemView.findViewById(R.id.left_msg);
            remind_word = itemView.findViewById(R.id.remind_word);
            rightMsg = itemView.findViewById(R.id.right_msg);
            self_send_image = itemView.findViewById(R.id.self_send_image);
            other_send_image = itemView.findViewById(R.id.other_send_image);
            self_avatar = itemView.findViewById(R.id.self_avatar);
            other_avatar = itemView.findViewById(R.id.other_avatar);
            self_file_desc = itemView.findViewById(R.id.self_file_desc);
            other_file_desc = itemView.findViewById(R.id.other_file_desc);
            self_file_image = itemView.findViewById(R.id.self_file_image);
            self_video_image = itemView.findViewById(R.id.self_video_image);
            other_video_image = itemView.findViewById(R.id.other_video_image);
            other_file_image = itemView.findViewById(R.id.other_file_image);
            self_file_linear = itemView.findViewById(R.id.self_file_linear);
            other_file_linear = itemView.findViewById(R.id.other_file_linear);
            self_play_video = itemView.findViewById(R.id.self_play_video);
            other_play_video = itemView.findViewById(R.id.other_play_video);
            self_video_relative = itemView.findViewById(R.id.self_video_relative);
            other_video_relative = itemView.findViewById(R.id.other_video_relative);
            other_sign = itemView.findViewById(R.id.other_sign);

            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();

        }
    }

    public MsgAdapter(List<Msg> msgList) {
        mMsgList = msgList;
    }

    @NonNull
    @Override
    public ViewHold onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item04, parent, false);
        return new ViewHold(view);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull ViewHold holder, int position) {
        holder.setIsRecyclable(false);
        fileSet = (Set<File>) GlobalAssistMap.getObject("fileSet");
        deleteFiles();

        Msg msg = mMsgList.get(position);//position是当前子项在集合中的位置，通过position参数得到当前项的Msg实例
        GlobalRoomBean globalRoomBean = GlobalChatRoomMap.getRoomInfo(msg.getRoomName());
        activity = globalRoomBean.getActivity();


        if (msg.getType() == Msg.TYPE_RECEIVE) {

            addSign(holder, msg);

            holder.remind_word.setVisibility(View.GONE);
            holder.self_avatar.setVisibility(View.GONE);
            //如果是收到的信息，则显示左边的布局信息，将右边的信息隐藏
            holder.self_file_linear.setVisibility(View.GONE);
            holder.self_video_relative.setVisibility(View.GONE);
            holder.self_file_desc.setVisibility(View.GONE);
            holder.other_play_video.setVisibility(View.GONE);
            holder.rightMsg.setVisibility(View.GONE);
            holder.self_file_image.setVisibility(View.GONE);
            holder.self_video_image.setVisibility(View.GONE);
            holder.rightLayout.setVisibility(View.GONE);
            holder.leftLayout.setVisibility(View.VISIBLE);
            if (msg.getFileType() == Msg.WORD_TYPE || msg.getFileType() == Msg.RECALL_TYPE) {
                holder.other_file_linear.setVisibility(View.GONE);
                holder.leftMsg.setVisibility(View.VISIBLE);
                holder.other_send_image.setVisibility(View.GONE);
                holder.other_file_desc.setVisibility(View.GONE);
                holder.other_file_image.setVisibility(View.GONE);
                holder.other_video_relative.setVisibility(View.GONE);
                holder.other_video_image.setVisibility(View.GONE);
                if (msg.getFileType() == Msg.RECALL_TYPE) {
                    holder.leftMsg.setText("此消息已撤回");
                    holder.leftMsg.setTextColor(Color.parseColor("#ff0000"));
                } else {
                    holder.leftMsg.setText(msg.getContent());
                }
            } else if (msg.getFileType() == Msg.Other_FILE_TYPE) {

                holder.leftMsg.setVisibility(View.GONE);

                GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        activity.runOnUiThread(new Runnable() {
                            @RequiresApi(api = Build.VERSION_CODES.O)
                            @Override
                            public void run() {

                                if (!isScrolling) {

                                    if (msg.getFileDesc() != null) {

                                        if (msg.getFileDesc().contains(".mp4 ")) {
                                            holder.other_file_linear.setVisibility(View.VISIBLE);
                                            holder.other_file_image.setVisibility(View.GONE);
                                            holder.other_file_desc.setVisibility(View.GONE);
                                            holder.other_send_image.setVisibility(View.GONE);
                                            holder.other_video_relative.setVisibility(View.VISIBLE);
                                            holder.other_video_image.setVisibility(View.VISIBLE);
                                            String videoCacheKey = msg.getImageUrl().substring(msg.getImageUrl().lastIndexOf("/") + 1);

                                            LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                            final Bitmap[] bitmap = {(Bitmap) lruCache.get(videoCacheKey)};
                                            //final Bitmap[] bitmap = {(Bitmap) GlobalAssistMap.getObject(videoCacheKey)};
                                            if (bitmap[0] == null) {

                                                activity.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        try {
                                                            Thread.sleep(200);
                                                            LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                                            bitmap[0] = (Bitmap) lruCache.get(videoCacheKey);
                                                            // bitmap[0] = (Bitmap) GlobalAssistMap.getObject(videoCacheKey);
                                                            if (bitmap[0] == null) {
                                                                Thread.sleep(300);
                                                                bitmap[0] = (Bitmap) lruCache.get(videoCacheKey);
                                                                //bitmap[0] = (Bitmap) GlobalAssistMap.getObject(videoCacheKey);
                                                                if (bitmap[0] == null) {
                                                                    Thread.sleep(500);
                                                                    bitmap[0] = (Bitmap) lruCache.get(videoCacheKey);
                                                                    //bitmap[0] = (Bitmap) GlobalAssistMap.getObject(videoCacheKey);
                                                                    if (bitmap[0] == null) {
                                                                        MessagesRequest.getVideoImage(msg.getImageUrl());
                                                                    }
                                                                }
                                                            }

                                                            if (bitmap[0] != null) {
                                                                receiveVideoOperation(bitmap[0], holder, activity, msg);
                                                            }

                                                        } catch (InterruptedException e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                });
                                            } else {
                                                receiveVideoOperation(bitmap[0], holder, activity, msg);
                                            }

                                        } else {
                                            holder.other_play_video.setVisibility(View.GONE);
                                            holder.other_video_image.setVisibility(View.GONE);
                                            holder.other_send_image.setVisibility(View.GONE);
                                            holder.other_video_relative.setVisibility(View.GONE);
                                            holder.other_file_linear.setVisibility(View.VISIBLE);
                                            holder.other_file_desc.setVisibility(View.VISIBLE);
                                            holder.other_file_image.setVisibility(View.VISIBLE);
                                            String fileDesc = msg.getFileDesc();
                                            String[] words = fileDesc.split(" ");
                                            if (words.length == 2) {
                                                fileDesc = words[0].length() > 20 ? words[0].substring(0, 15) + "..." + words[0].substring(words[0].lastIndexOf(".") - 1) + " " + words[1] : fileDesc;
                                            } else {
                                                fileDesc = fileDesc.length() > 20 ? fileDesc.substring(0, 8) + "..." + fileDesc.substring(fileDesc.length() - 12) : fileDesc;
                                            }
                                            holder.other_file_desc.setText(fileDesc);
                                            if (msg.getFileDesc().contains(".txt ")) {
                                                holder.other_file_image.setBackgroundResource(R.drawable.img_20);
                                            } else if (msg.getFileDesc().contains(".docx ")) {
                                                holder.other_file_image.setBackgroundResource(R.drawable.img_22);
                                            } else if (msg.getFileDesc().contains(".ppt ")) {
                                                holder.other_file_image.setBackgroundResource(R.drawable.img_27);
                                            } else if (msg.getFileDesc().contains(".mp3 ")) {
                                                holder.other_file_image.setBackgroundResource(R.drawable.img_28);
                                            } else if (msg.getFileDesc().contains(".apk ")) {
                                                holder.other_file_image.setBackgroundResource(R.drawable.img_31);
                                            } else if (msg.getFileDesc().contains(".pdf ")) {
                                                holder.other_file_image.setBackgroundResource(R.drawable.img_32);
                                            } else if (msg.getFileDesc().contains(".xlsx ") || msg.getFileDesc().contains(".xls ")) {
                                                holder.other_file_image.setBackgroundResource(R.drawable.img_33);
                                            }

                                            receiveFileOperation(holder, msg);
                                        }

                                    } else {
                                        holder.other_send_image.setVisibility(View.VISIBLE);
                                        holder.other_file_linear.setVisibility(View.GONE);
                                        holder.other_video_image.setVisibility(View.GONE);
                                        holder.other_play_video.setVisibility(View.GONE);
                                        holder.other_file_image.setVisibility(View.GONE);
                                        holder.other_file_desc.setVisibility(View.GONE);

                                        LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                        final Bitmap[] bitmap = {(Bitmap) lruCache.get(msg.getImageUrl())};
                                        //final Bitmap[] bitmap = {(Bitmap) GlobalAssistMap.getObject(msg.getImageUrl())};
                                        if (bitmap[0] == null) {
                                            activity.runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        Thread.sleep(150);
                                                        bitmap[0] = (Bitmap) lruCache.get(msg.getImageUrl());
                                                        //bitmap[0] = (Bitmap) GlobalAssistMap.getObject(msg.getImageUrl());
                                                        if (bitmap[0] == null) {
                                                            MessagesRequest.getImage(Constant.IMAGE_SERVER_PATH + msg.getImageUrl(), new Handler(new Handler.Callback() {
                                                                @Override
                                                                public boolean handleMessage(@NonNull Message message) {
                                                                    bitmap[0] = (Bitmap) lruCache.get(msg.getImageUrl());
                                                                    holder.other_send_image.setImageBitmap(bitmap[0]);
                                                                    return true;
                                                                }
                                                            }));
                                                        } else {
                                                            holder.other_send_image.setImageBitmap(bitmap[0]);
                                                        }
                                                        holder.other_send_image.setOnClickListener(new View.OnClickListener() {
                                                            @Override
                                                            public void onClick(View view) {
                                                                GlobalRoomBean globalRoomBean = GlobalChatRoomMap.getRoomInfo(msg.getRoomName());
                                                                if (!msg.isOneToOne()) {
                                                                    ChatActivity chatActivity = (ChatActivity) globalRoomBean.getActivity();
                                                                    chatActivity.showImage(msg.getImageUrl());
                                                                    return;
                                                                }
                                                                OneToOneChatActivity oneToOneChatActivity = (OneToOneChatActivity) globalRoomBean.getActivity();
                                                                oneToOneChatActivity.showImage(msg.getImageUrl());

                                                            }
                                                        });
                                                    } catch (InterruptedException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                        } else {
                                            holder.other_send_image.setImageBitmap(bitmap[0]);
                                            holder.other_send_image.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View view) {
                                                    GlobalRoomBean globalRoomBean = GlobalChatRoomMap.getRoomInfo(msg.getRoomName());
                                                    if (!msg.isOneToOne()) {
                                                        ChatActivity chatActivity = (ChatActivity) globalRoomBean.getActivity();
                                                        chatActivity.showImage(msg.getImageUrl());
                                                        return;
                                                    }
                                                    OneToOneChatActivity oneToOneChatActivity = (OneToOneChatActivity) globalRoomBean.getActivity();
                                                    oneToOneChatActivity.showImage(msg.getImageUrl());

                                                }
                                            });
                                        }
                                    }
                                }
                            }
                        });
                    }
                });
            }
            holder.other_avatar.setVisibility(View.VISIBLE);
            String avatarPath = msg.getAvatarPath();
            if (avatarPath.contains("/")) {
                Bitmap bitmap = BitmapFactory.decodeFile(avatarPath);
                holder.other_avatar.setImageBitmap(bitmap);
            } else {
                holder.other_avatar.setImageResource(Integer.parseInt(avatarPath));
            }
            holder.other_avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    UserInfoRequest.doGetUserInfoRequest(new Handler(new Handler.Callback() {
                        @Override
                        public boolean handleMessage(@NonNull Message message) {

                            UserInfoBean userInfoBean = (UserInfoBean) message.obj;
                            if (userInfoBean != null) {
                                GlobalAssistMap.putObject(msg.getSenderId() + "Info", userInfoBean);
                                Intent intent = new Intent();
                                intent.setClass(activity, UserInfoActivity.class);
                                intent.putExtra("senderId", userInfoBean.getId());
                                intent.putExtra("senderAvatar", msg.getAvatarPath());
                                intent.putExtra("senderSign", holder.other_sign.getText());
                                activity.startActivityForResult(intent, USER_INFO_CODE);
                            }
                            return true;
                        }
                    }), msg.getSenderId());
                }
            });

        } else if (msg.getType() == Msg.TYPE_SEND) {

            holder.remind_word.setVisibility(View.GONE);

            holder.other_avatar.setVisibility(View.GONE);
            //若是发出的信息，则显示右边的布局信息，隐藏左边的布局信息
            holder.leftLayout.setVisibility(View.GONE);
            holder.rightLayout.setVisibility(View.VISIBLE);
            holder.other_file_linear.setVisibility(View.GONE);
            holder.other_file_image.setVisibility(View.GONE);
            holder.other_file_desc.setVisibility(View.GONE);
            holder.other_video_relative.setVisibility(View.GONE);
            holder.other_play_video.setVisibility(View.GONE);
            holder.other_play_video.setVisibility(View.GONE);
            holder.other_sign.setVisibility(View.GONE);

            if (msg.getFileType() == Msg.WORD_TYPE || msg.getFileType() == Msg.RECALL_TYPE) {
                holder.rightMsg.setVisibility(View.VISIBLE);
                holder.self_send_image.setVisibility(View.GONE);
                holder.self_file_linear.setVisibility(View.GONE);
                holder.self_file_image.setVisibility(View.GONE);
                holder.self_file_desc.setVisibility(View.GONE);
                holder.self_video_relative.setVisibility(View.GONE);
                holder.self_video_image.setVisibility(View.GONE);
                holder.self_play_video.setVisibility(View.GONE);
                holder.rightMsg.setText(msg.getContent());
                if (msg.getFileType() == Msg.RECALL_TYPE) {
                    holder.rightMsg.setText("此消息已撤回");
                    holder.rightMsg.setTextColor(Color.parseColor("#ff0000"));
                }

                if (msg.getFileType() == Msg.RECALL_TYPE && msg.getImageUrl() == null) {
                    holder.rightMsg.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                        @Override
                        public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                            contextMenu.add(0, 1, 0, "重新编辑");
                            GlobalAssistMap.putObject("selectMsg", msg);
                        }
                    });
                }


            } else {
                holder.rightMsg.setVisibility(View.GONE);
                GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!isScrolling) {

                                    if (msg.getFileDesc() != null) {

                                        holder.self_send_image.setVisibility(View.GONE);
                                        holder.leftMsg.setVisibility(View.GONE);
                                        holder.self_file_linear.setVisibility(View.VISIBLE);

                                        if (msg.getFileDesc().contains(".mp4 ")) {
                                            holder.self_video_relative.setVisibility(View.VISIBLE);
                                            holder.self_file_image.setVisibility(View.GONE);
                                            holder.self_video_image.setVisibility(View.VISIBLE);
                                            holder.self_file_desc.setVisibility(View.GONE);
                                            String videoCacheKey = msg.getImageUrl().substring(msg.getImageUrl().lastIndexOf("/") + 1, msg.getImageUrl().lastIndexOf(".")) + ".jpeg";

                                            LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                            final Bitmap[] bitmap = {(Bitmap) lruCache.get(videoCacheKey)};
                                            // final Bitmap[] bitmap = {(Bitmap) GlobalAssistMap.getObject(videoCacheKey)};
                                            if (bitmap[0] == null) {

                                                activity.runOnUiThread(new Runnable() {
                                                    @RequiresApi(api = Build.VERSION_CODES.O)
                                                    @Override
                                                    public void run() {
                                                        try {
                                                            Thread.sleep(200);
                                                            bitmap[0] = (Bitmap) lruCache.get(videoCacheKey);
                                                            //bitmap[0] = (Bitmap) GlobalAssistMap.getObject(videoCacheKey);
                                                            if (bitmap[0] == null) {
                                                                MessagesRequest.getVideoImage(Constant.VIDEO_SERVER_PATH + msg.getImageUrl().substring(msg.getImageUrl().lastIndexOf("/") + 1));
                                                            }

                                                            if (bitmap[0] != null) {
                                                                sendVideoOperation(holder, msg, activity, bitmap[0]);
                                                            }

                                                        } catch (InterruptedException e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                });
                                            } else {
                                                sendVideoOperation(holder, msg, activity, bitmap[0]);
                                            }

                                        } else {

                                            holder.self_file_desc.setVisibility(View.VISIBLE);
                                            holder.self_file_image.setVisibility(View.VISIBLE);
                                            holder.self_video_image.setVisibility(View.GONE);
                                            holder.self_video_relative.setVisibility(View.GONE);
                                            holder.self_play_video.setVisibility(View.GONE);
                                            String fileDesc = msg.getFileDesc();
                                            String[] words = fileDesc.split(" ");
                                            fileDesc = words[0].length() > 20 ? words[0].substring(0, 15) + "..." + words[0].substring(words[0].lastIndexOf(".") - 1) + " " + words[1] : fileDesc;
                                            holder.self_file_desc.setText(fileDesc);

                                            if (msg.getFileDesc().contains(".txt ")) {
                                                holder.self_file_image.setBackgroundResource(R.drawable.img_20);
                                            } else if (msg.getFileDesc().contains(".docx ")) {
                                                holder.self_file_image.setBackgroundResource(R.drawable.img_22);
                                            } else if (msg.getFileDesc().contains(".ppt ")) {
                                                holder.self_file_image.setBackgroundResource(R.drawable.img_27);
                                            } else if (msg.getFileDesc().contains(".mp3 ")) {
                                                holder.self_file_image.setBackgroundResource(R.drawable.img_28);
                                            } else if (msg.getFileDesc().contains(".apk ")) {
                                                holder.self_file_image.setBackgroundResource(R.drawable.img_31);
                                            } else if (msg.getFileDesc().contains(".pdf ")) {
                                                holder.self_file_image.setBackgroundResource(R.drawable.img_32);
                                            } else if (msg.getFileDesc().contains(".xlsx ") || msg.getFileDesc().contains(".xls ")) {
                                                holder.self_file_image.setBackgroundResource(R.drawable.img_33);
                                            }
                                            holder.self_file_linear.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View view) {
                                                    String fileLocalPath = msg.getImageUrl();
                                                    File file = new File(fileLocalPath);
                                                    if (!file.exists()) {
                                                        AlterUtils.alertByToastInMainThread(activity, "文件已经不存在了");
                                                        return;
                                                    }
                                                    fileOperation(activity, msg, file);
                                                }
                                            });
                                        }

                                    } else {
                                        holder.self_file_linear.setVisibility(View.GONE);
                                        holder.self_file_image.setVisibility(View.GONE);
                                        holder.self_video_relative.setVisibility(View.GONE);
                                        holder.self_video_image.setVisibility(View.GONE);
                                        holder.self_play_video.setVisibility(View.GONE);
                                        holder.self_send_image.setVisibility(View.VISIBLE);
                                        holder.self_file_desc.setVisibility(View.GONE);

                                        String cacheKey = msg.getImageUrl().substring(msg.getImageUrl().lastIndexOf("/") + 1);
                                        LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                        Bitmap bitmap = (Bitmap) lruCache.get(cacheKey);
                                        //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(cacheKey);
                                        if (bitmap == null) {
                                            bitmap = BitmapFactory.decodeFile(msg.getImageUrl());
                                            if (bitmap != null) {
                                                lruCache.put(cacheKey, bitmap);
                                                // GlobalAssistMap.putObject(cacheKey, bitmap);
                                            }
                                        }
                                        holder.self_send_image.setImageBitmap(bitmap);
                                        holder.self_send_image.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                GlobalRoomBean globalRoomBean = GlobalChatRoomMap.getRoomInfo(msg.getRoomName());
                                                if (!msg.isOneToOne()) {
                                                    ChatActivity chatActivity = (ChatActivity) globalRoomBean.getActivity();
                                                    chatActivity.showImage(msg.getImageUrl());
                                                    return;
                                                }
                                                OneToOneChatActivity oneToOneChatActivity = (OneToOneChatActivity) globalRoomBean.getActivity();
                                                oneToOneChatActivity.showImage(msg.getImageUrl());

                                            }
                                        });


                                    }
                                }
                            }
                        });
                    }
                });
            }
            String avatarStr = msg.getAvatarPath();
            holder.self_avatar.setVisibility(View.VISIBLE);
            if (avatarStr.contains("/")) {

                LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                Bitmap bitmap = (Bitmap) lruCache.get(avatarStr.substring(avatarStr.lastIndexOf("/")));
                // Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(avatarStr.substring(avatarStr.lastIndexOf("/")));
                if (bitmap == null) {
                    bitmap = BitmapFactory.decodeFile(avatarStr);

                    lruCache.put(avatarStr.substring(avatarStr.lastIndexOf("/")), bitmap);
                    // GlobalAssistMap.putObject(avatarStr.substring(avatarStr.lastIndexOf("/")), bitmap);
                }
                holder.self_avatar.setImageBitmap(bitmap);
            } else {
                holder.self_avatar.setImageResource(Integer.parseInt(msg.getAvatarPath()));
            }

            holder.self_avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setClass(activity, UserInfoActivity.class);
                    activity.startActivityForResult(intent, UPDATE_INFO_CODE);
                }
            });


            if (msg.getFileType() != Msg.RECALL_TYPE) {
                holder.rightMsg.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        GlobalRoomBean roomInfo = GlobalChatRoomMap.getRoomInfo(msg.getRoomName());
                        Activity activity = roomInfo.getActivity();
                        DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (!judgeMsgIdExist(msg)) return;
                                holder.rightMsg.setText("此消息已撤回");
                                holder.rightMsg.setTextColor(Color.parseColor("#ff0000"));
                                recall(msg);
                            }
                        };

                        DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        };
                        if (msg.getFileType() != Msg.RECALL_TYPE) {
                            AlterUtils.alertByDialog(activity, "提示", "确定撤回此消息吗?", "确定", positiveListener, "取消", cancelListener);
                        }
                        return true;
                    }
                });

                holder.self_send_image.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        GlobalRoomBean roomInfo = GlobalChatRoomMap.getRoomInfo(msg.getRoomName());
                        Activity activity = roomInfo.getActivity();
                        DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (!judgeMsgIdExist(msg)) return;
                                holder.self_send_image.setVisibility(View.GONE);
                                holder.rightMsg.setVisibility(View.VISIBLE);
                                holder.rightMsg.setText("此消息已撤回");
                                holder.rightMsg.setTextColor(Color.parseColor("#ff0000"));
                                recall(msg);
                            }
                        };

                        DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        };

                        if (msg.getFileType() != Msg.RECALL_TYPE) {
                            AlterUtils.alertByDialog(activity, "提示", "确定撤回此消息吗?", "确定", positiveListener, "取消", cancelListener);
                        }
                        return true;
                    }
                });

                holder.self_file_linear.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        GlobalRoomBean roomInfo = GlobalChatRoomMap.getRoomInfo(msg.getRoomName());
                        Activity activity = (Activity) roomInfo.getActivity();
                        DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (!judgeMsgIdExist(msg)) return;
                                holder.self_file_linear.setVisibility(View.GONE);
                                holder.rightMsg.setVisibility(View.VISIBLE);
                                holder.rightMsg.setText("此消息已撤回");
                                holder.rightMsg.setTextColor(Color.parseColor("#ff0000"));
                                recall(msg);
                            }
                        };

                        DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        };
                        if (msg.getFileType() != Msg.RECALL_TYPE) {
                            AlterUtils.alertByDialog(activity, "提示", "确定撤回此消息吗?", "确定", positiveListener, "取消", cancelListener);
                        }
                        return true;
                    }
                });

            }


        } else if (msg.getType() == Msg.TYPE_REMIND) {

            holder.remind_word.setVisibility(View.VISIBLE);

            holder.self_avatar.setVisibility(View.GONE);
            holder.self_file_desc.setVisibility(View.GONE);
            holder.rightMsg.setVisibility(View.GONE);
            holder.leftLayout.setVisibility(View.GONE);
            holder.self_file_linear.setVisibility(View.GONE);
            holder.self_file_image.setVisibility(View.GONE);
            holder.self_video_relative.setVisibility(View.GONE);
            holder.self_play_video.setVisibility(View.GONE);
            holder.self_video_image.setVisibility(View.GONE);
            holder.self_send_image.setVisibility(View.GONE);


            holder.other_avatar.setVisibility(View.GONE);
            holder.other_file_desc.setVisibility(View.GONE);
            holder.leftMsg.setVisibility(View.GONE);
            holder.rightLayout.setVisibility(View.VISIBLE);
            holder.other_file_linear.setVisibility(View.GONE);
            holder.other_file_image.setVisibility(View.GONE);
            holder.other_video_relative.setVisibility(View.GONE);
            holder.other_play_video.setVisibility(View.GONE);
            holder.other_sign.setVisibility(View.GONE);
            holder.other_video_image.setVisibility(View.GONE);
            holder.other_send_image.setVisibility(View.GONE);


            String[] words = msg.getContent().split("\\|");
            String userName = words[1];
            if (words[0].equals("")) {
                holder.remind_word.setText(userName + "撤回了一条消息");
                return;
            }
            int count = Integer.parseInt(words[0]);
            String content = userName + (count < 0 ? "离开群聊" : "加入群聊");
            holder.remind_word.setText(content);

        }


    }

    private boolean judgeMsgIdExist(Msg msg) {
        if (msg.getId() == 0) {
            try {
                Thread.sleep(150);
                if (msg.getId() == 0) {
                    Thread.sleep(300);
                    if (msg.getId() == 0) {
                        Thread.sleep(500);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (msg.getId() == 0) {
            return false;
        }
        return true;
    }

    private void recall(Msg msg) {


        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                GlobalRoomBean roomInfo = GlobalChatRoomMap.getRoomInfo(msg.getRoomName());
                Activity activity = roomInfo.getActivity();
                List<Msg> msgList = roomInfo.getMsgList();
                RecyclerView msgRecyclerView = roomInfo.getMsgRecyclerView();
                Msg newMsg = null;
                for (int i = 0; i < msgList.size(); i++) {
                    if (msg == msgList.get(i)) {

                        if (msg.getFileType() == Msg.WORD_TYPE) {
                            newMsg = new Msg(msg.getSenderId(), msg.getRoomName(), Msg.RECALL_TYPE, msg.getContent(), Msg.TYPE_SEND, msg.getAvatarPath(), msg.isOneToOne());
                        } else {
                            newMsg = new Msg(msg.getSenderId(), Msg.TYPE_SEND, Msg.RECALL_TYPE, "", msg.getRoomName(), msg.getAvatarPath(), null, msg.isOneToOne());
                        }
                        newMsg.setId(msg.getId());
                        msgList.remove(i);
                        msgList.add(i, newMsg);
                        break;
                    }
                }
                msg.setFileType(Msg.RECALL_TYPE);
                MsgAdapter adapter = new MsgAdapter(msgList);
                GlobalRoomBean globalRoomBean = new GlobalRoomBean();
                globalRoomBean.setRoomName(msg.getRoomName());
                globalRoomBean.setAdapter(adapter);
                globalRoomBean.setMsgList(msgList);
                globalRoomBean.setActivity(activity);
                globalRoomBean.setMsgRecyclerView(msgRecyclerView);
                GlobalChatRoomMap.putRoomInfo(msg.getRoomName(), globalRoomBean);

            }
        });


        MessageBean messageBean = new MessageBean();
        messageBean.setActionType(ActionType.CHAT_TYPE);
        messageBean.setMsgType(8);

        if (msg.isOneToOne()) {
            String roomName = msg.getRoomName();
            int sumNum = Integer.parseInt(roomName.substring(0, roomName.indexOf("c")));
            int receiverId = sumNum - Integer.parseInt(msg.getSenderId());
            messageBean.setReceiverId(String.valueOf(receiverId));
        }
        messageBean.setOneToOne(msg.isOneToOne());
        messageBean.setRoomName(msg.getRoomName());
        messageBean.setMsg(msg);
        UserInfoBean userInfoBean = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
        messageBean.setField(GlobalAssistMap.getObject("field").toString());
        messageBean.setSenderId(String.valueOf(userInfoBean.getId()));
        @SuppressLint("SimpleDateFormat") String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        messageBean.setSendTime(time);
        messageBean.setSenderAvatarPath(userInfoBean.getAvatarUrl());
        messageBean.setSenderName(userInfoBean.getNickname());
        NettyClient.getInstance().sendMessage(messageBean);

    }

    @SuppressLint("SetTextI18n")
    private void addSign(@NonNull ViewHold holder, Msg msg) {
        final UserInfoBean[] userInfoBean = {(UserInfoBean) GlobalAssistMap.getObject(msg.getSenderId() + "Info")};
        if (userInfoBean[0] == null) {

            activity.runOnUiThread(new Runnable() {
                @SuppressLint("SetTextI18n")
                @Override
                public void run() {
                    if (hasSenderInfo(msg.getSenderId())) {
                        userInfoBean[0] = (UserInfoBean) GlobalAssistMap.getObject(msg.getSenderId() + "Info");
                        String nickName = userInfoBean[0].getNickname();
                        String sign = userInfoBean[0].getSign();
                        holder.other_sign.setVisibility(View.VISIBLE);
                        sign = (sign == null || sign.equals("")) ? "" : ":" + sign;
                        String mark = nickName + sign;
                        mark = mark.length() > 22 ? mark.substring(0, 22) + "..." : mark;
                        holder.other_sign.setText(mark);
                    } else {
                        holder.other_sign.setVisibility(View.GONE);
                    }

                }
            });

        } else {
            String nickName = userInfoBean[0].getNickname();
            String sign = userInfoBean[0].getSign();
            holder.other_sign.setVisibility(View.VISIBLE);
            sign = (sign == null || sign.equals("")) ? "" : ":" + sign;
            String mark = nickName + sign;
            mark = mark.length() > 22 ? mark.substring(0, 22) + "..." : mark;
            holder.other_sign.setText(mark);
        }
    }

    private boolean hasSenderInfo(String senderId) {

        final UserInfoBean[] userInfoBean = {(UserInfoBean) GlobalAssistMap.getObject(senderId + "Info")};
        if (userInfoBean[0] == null) {
            CountDownLatch countDownLatch = new CountDownLatch(1);
            UserInfoRequest.doGetUserInfoRequest(new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message message) {
                    userInfoBean[0] = (UserInfoBean) GlobalAssistMap.getObject(senderId + "Info");
                    countDownLatch.countDown();
                    return true;
                }
            }), senderId);
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return userInfoBean[0] != null;
    }

    private void receiveFileOperation(@NonNull ViewHold holder, Msg msg) {
        final boolean[] notLoad = {true};
        final boolean[] isFirst = {true};
        holder.other_file_linear.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View view) {
                File file = new File(Constant.FILE_PATH + msg.getImageUrl().substring(msg.getImageUrl().lastIndexOf("/") + 1));
                if (!file.exists()) {

                    if (!isFirst[0] && notLoad[0]) {
                        AlterUtils.alertByToastInMainThread(activity, "正在加载中");
                        return;
                    }
                    isFirst[0] = false;

                    MessagesRequest.getFile(new Handler(new Handler.Callback() {
                        @Override
                        public boolean handleMessage(@NonNull Message message) {

                            if (Constant.SUCCESS.equals((String) message.obj)) {
                                fileOperation(activity, msg, file);
                                notLoad[0] = false;
                            }
                            return true;
                        }
                    }), msg.getImageUrl());
                } else {
                    fileOperation(activity, msg, file);
                }
            }
        });
    }


    @Override
    public int getItemCount() {
        return mMsgList.size();
    }


    public void setScrolling(boolean scrolling) {
        isScrolling = scrolling;
    }


    private void fileOperation(Activity activity, Msg msg, File file) {
        if (msg.getFileDesc().contains(".txt ")) {
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "text/plain");
            activity.startActivity(intent);
        } else if (msg.getFileDesc().contains(".docx ")) {
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/msword");
            activity.startActivity(intent);
        } else if (msg.getFileDesc().contains(".ppt ")) {
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
            activity.startActivity(intent);
        } else if (msg.getFileDesc().contains(".mp3 ")) {
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("oneshot", 0);
            intent.putExtra("configchange", 0);
            if (msg.getType() == Msg.TYPE_RECEIVE) {
                fileSet.add(file);
            }
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "audio/*");
            activity.startActivity(intent);
        } else if (msg.getFileDesc().contains(".apk ")) {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            activity.startActivity(intent);
        } else if (msg.getFileDesc().contains(".pdf ")) {
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/pdf");
            activity.startActivity(intent);
        } else if (msg.getFileDesc().contains(".xlsx ") || msg.getFileDesc().contains(".xls ")) {
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.ms-excel");
            activity.startActivity(intent);
        }
    }


    private void receiveVideoOperation(Bitmap bm, @NonNull ViewHold holder, Activity activity, Msg msg) {
        holder.other_video_image.setImageBitmap(bm);
        holder.other_play_video.setVisibility(View.VISIBLE);
        holder.other_play_video.setBackgroundResource(R.drawable.play);
        final boolean[] notLoad = {true};
        final boolean[] isFirst = {true};
        holder.other_video_relative.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View view) {

                if (!isFirst[0] && notLoad[0]) {
                    AlterUtils.alertByToastInMainThread(activity, "正在加载中");
                    return;
                }
                isFirst[0] = false;

                String filePath = msg.getImageUrl().substring(0, msg.getImageUrl().lastIndexOf(".")) + ".mp4";

                MessagesRequest.getVideo(new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(@NonNull Message message) {

                        String res = (String) message.obj;
                        if (Constant.SUCCESS.equals(res)) {
                            String localVideoPath = Constant.VIDEO_PATH + filePath.substring(filePath.lastIndexOf("/") + 1);
                            File file = new File(localVideoPath);
                            if (file.exists()) {
                                Intent intent = new Intent("android.intent.action.VIEW");
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                intent.putExtra("oneshot", 0);
                                intent.putExtra("configchange", 0);
                                Uri uri = Uri.fromFile(file);
                                intent.setDataAndType(uri, "video/*");
                                fileSet.add(file);
                                notLoad[0] = false;
                                activity.startActivity(intent);
                            }
                        }

                        return true;
                    }
                }), filePath);

            }
        });
    }


    private void sendVideoOperation(@NonNull ViewHold holder, Msg msg, Activity activity, Bitmap bm) {
        holder.self_video_image.setImageBitmap(bm);
        holder.self_play_video.setBackgroundResource(R.drawable.play);
        holder.self_play_video.setVisibility(View.VISIBLE);

        holder.self_file_linear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File file = new File(msg.getImageUrl());
                if (file.exists()) {
                    Intent intent = new Intent("android.intent.action.VIEW");
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra("oneshot", 0);
                    intent.putExtra("configchange", 0);
                    Uri uri = Uri.fromFile(file);
                    intent.setDataAndType(uri, "video/*");
                    activity.startActivity(intent);
                }
            }
        });
    }


    public void deleteFiles() {

        if (fileSet.size() > 0) {
            GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    synchronized (MsgAdapter.class) {
                        Iterator<File> iterator = fileSet.iterator();
                        while (iterator.hasNext()) {
                            File file = iterator.next();
                            if (file.exists()) {
                                try {
                                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                                    bufferedOutputStream.write(new byte[0]);
                                    iterator.remove();
                                    file.delete();
                                    bufferedOutputStream.flush();
                                    bufferedOutputStream.close();
                                    fileOutputStream.close();

                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            });
        }
    }


}
